<?
/**
 * Description Ranking:
 *
 * @author Ferran Martin
 */
class Url {

    /*Settings*/
    private $mVars = array(
        array(0,"comprovarSeccio"),
        array(1,"comprovarVarsRestants")
    );

    private $aSeccions = array( //El primer es el modul que estara en el HOME
        "home"          => array('', 'beta'),
        "sitemap"       => array('sitemap'),
        "error"         => array('error404'),
        "reset"         => array('reset'),
        "tutorial"	=> array('tutorial'),
        "backend"       => array('backend')
    );

    private $aFunctionsSeccions = array(
        "ingame"        => "comprovarParsVars",
        "backend"       => "comprovarParsVars_BackEnd"
    );

    private $VariablesGet = array(
        "web" => array(                 //Dades generals de la web
            "url"   => "/",                 //URL de la web
            "path"  => ""                   //Path de la web
        ),
        "seccio" => array(              //Dades del modul a carregar
            "modul" => "",                  //nom d'arxiu del modul (sense extensio),
            "url"   => "",                  //String amb url del modul amb l'idioma actual
            "vars"  => array()              //la resta de variables que s'agin escrit, cada modul a de comprovar les seves.
        )

    );

    private $aVariables = array();

    private $NomHost = "";
    private $oUser;


    public function  __construct($NomHost, &$oUser, $href = "") {
        $this->NomHost = $NomHost;
        $this->oUser = $oUser;

        $this->setVariables($href);
    }

    public function getVariables($url = "") {
        if (empty($url)) return $this->VariablesGet;
        else return $this->setVariables ($url);
    }

    public function getHome(){
        return array_shift(array_keys($this->aSeccions));
    }

    public function redirect($url = "") {
        Header( "HTTP/1.1 301 Moved Permanently" );
        Header( "Location: ".$this->NomHost.$url );
    }

    private function setVariables($url) {

            //En alguns servers el rewrite en la base / retorna a route=index.php; s'ha de comprovar per saber igualemnt si estem en home o no
            if ($url == "index.php") $url = "";

            //treiem la barra del final
            $url = preg_replace('/\/$/', '', $url);
            //treiem la barra del principi
            $url = preg_replace('/^\//', '', $url);

            //separamos las partes/variables de la url y las contamos
            $variables = explode('/', $url);

            for ($c = 0; $c < count($variables); $c++){
                    //Acumulamos los valores limpios en un arreglo
                    //$variables[$c] = cleanVariables(strtolower($variables[$c]));
                    $variables[$c] = $this->cleanVariables($variables[$c]);
            }
            $this->aVariables = $variables;
            $this->VariablesGet["web"]["path"] = $this->NomHost.$url;

            foreach( $this->mVars as $keysVar => $Var) {
                eval("\$this->".$Var[1]."(".$Var[0].");");
            }

            return $this->VariablesGet;
    }

    private function comprovarSeccio($index){

        $bFound = false;
        foreach ($this->aSeccions as $Modul => $aSeccio) {
            if (in_array($this->aVariables[$index], $aSeccio)) { //Hem trobat el modul corresponent
                $this->VariablesGet["seccio"]["modul"] = $Modul;
                $this->VariablesGet["seccio"]["url"] = $aSeccio[array_search($this->aVariables[$index], $aSeccio)];
                $bFound = true;
            }
        }

        if (!$bFound) {
            //Buscar si es nom d'equip
            $oTeam = new Team();
            if ($idTeam = $oTeam->isTeamName($this->aVariables[$index])) {
                $idUser = $this->oUser->getOwnTeam($idTeam);
                $this->VariablesGet["seccio"]["modul"] = "ingame";
                $this->VariablesGet["seccio"]["url"] = $this->aVariables[$index];
                $this->correrVarsArray($index);
                $this->aVariables[$index] = $idUser;
            }
            else {
                $this->VariablesGet["seccio"]["modul"] = $this->getHome();
                $this->VariablesGet["seccio"]["url"] = "";
            }            

            $this->correrVarsArray($index);
        }
    }

    private function comprovarVarsRestants($index){

        $aVars = array();
        for ($i = $index ; $i < count($this->aVariables) ; $i++) $aVars[$i-$index] = $this->aVariables[$i];
        $this->VariablesGet["seccio"]["vars"] = $aVars;
        if ($this->aFunctionsSeccions[$this->VariablesGet["seccio"]["modul"]]) {
            eval("\$this->".$this->aFunctionsSeccions[$this->VariablesGet["seccio"]["modul"]]."();");
        }

    }

    private function comprovarParsVars(){
        //de $this->VariablesGet["seccio"]["vars"]
        //a $this->VariablesGet["seccio"]["vars-res"]

        $aVarsNews = array();
        $aVars = $this->VariablesGet["seccio"]["vars"];
        $count = count($aVars);
        for($i = 3; $i < $count; $i = $i+2) {
            $aVarsNews[$aVars[$i]] = $aVars[$i+1];
            $sVars .= "/".$aVars[$i]."/".$aVars[$i+1];
        }
        $this->VariablesGet["seccio"]["vars-res"] = $aVarsNews;
        $this->VariablesGet["seccio"]["vars-res_path"] = $sVars;

    }

    private function comprovarParsVars_BackEnd() {
        //de $this->VariablesGet["seccio"]["vars"]
        //a $this->VariablesGet["seccio"]["vars-res"]
        $aVarsNews = array();
        $aVars = $this->VariablesGet["seccio"]["vars"];
        $count = count($aVars);
        for($i = 0; $i < $count; $i = $i+2) {
            $aVarsNews[$aVars[$i]] = $aVars[$i+1];
            $sVars .= "/".$aVars[$i]."/".$aVars[$i+1];
        }
        $this->VariablesGet["seccio"]["vars-res"] = $aVarsNews;
        $this->VariablesGet["seccio"]["vars-res_path"] = $sVars;
    }

    private function correrVarsArray($index) {

        for ($i = count($this->aVariables) ; $i > $index ; $i--) $this->aVariables[$i] = $this->aVariables[$i-1];
        $this->aVariables[$index] = "";

    }

    private function redirect_error($path = "") {
        Header( "HTTP/1.1 301 Moved Permanently" );
        Header( "Location: ".$this->NomHost.$path."error404" );
    }

    private  function cleanVariables($valor){
        //permitimos solo letras(a-Z), numeros, guiones
        return preg_replace('/[^a-zA-Z0-9-_:><]/', '', $valor);
    }
}

?>